package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//使用这个类封装针对user表增删改查
public class UserDao {
    //对于新增User,主要就是要实现一个"注册的功能"，当前不打算写
    //对于原先的User,主要是去实现一个"注销的功能"，当前不打算写
    //1.根据userId来查询用户信息（后续根据博客查询出作者详情）
    public  User getUserById(int userId){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection=DBUtil.getConnection();
            String sql="select *from user where userId=?";
            statement= connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet=statement.executeQuery();
            if(resultSet.next()){
                User user=new User();
                user.setUseId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
    //2.根据username来查询用户信息（实现登入效果）
    public User getUserByname(String username){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try{
            connection=DBUtil.getConnection();
            String sql="select* from user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet=statement.executeQuery();
            if (resultSet.next()){
                User user=new User();
                user.setUseId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        }catch ( SQLException throwables){
            throwables.printStackTrace();
        }
        finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
}
